from datetime import datetime

from flask import render_template, Blueprint, redirect, flash, url_for, request
from flask_login import login_required, logout_user, login_user

from app.ext import login_manager
from app.models import PDMFileModel, PDMModuleModel, PDMTableModel, PDMColumnModel, User

app_bp = Blueprint('app', __name__)

@app_bp.context_processor
def inject_globals():
    """注入全局模板变量"""
    # 获取年
    year = datetime.now().year
    return {
        'app_name': 'PDM阅读器',
        'current_year': f'2023-{year}',
        'by': '林默'
    }

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


@app_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = User.query.filter_by(username=username).first()

        if user and user.check_password(password):
            login_user(user)
            flash("登录成功", "success")
            return redirect(url_for('app.index'))
        else:
            flash("用户名或密码错误", "danger")
            return render_template('login.html')

    return render_template('login.html')


@app_bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('app.login'))


@app_bp.route('/', methods=['GET', 'POST'])
@app_bp.route('/index', methods=['GET', 'POST'])
@login_required
def index():
    pdm_file = PDMFileModel.get_all_files()

    pdm_info = [file.to_dict() for file in pdm_file]

    return render_template('index.html', pdms=pdm_info)


@app_bp.route('/package/<pdm_id>/', methods=['GET', 'POST'])
@login_required
def show_modules(pdm_id):
    pdm_file = PDMFileModel.get_file_by_id(pdm_id)
    pdm_info = pdm_file.to_dict()
    packages = PDMModuleModel.get_packages(pdm_id)
    modules = [package.to_dict() for package in packages]
    data = {
        "pdm_info": pdm_info,
        "modules": modules
    }
    print(data.get("pdm_info"))
    return render_template('package.html', data=data)


@app_bp.route('/tables/<pack_fid>/<pdm_id>/', methods=['GET', 'POST'])
@login_required
def list_tables(pack_fid, pdm_id):
    package = PDMModuleModel.get_package_tables(pack_fid, pdm_id)
    table_ids = package.table_ids
    table_list = []
    for t_id in table_ids:
        tables = PDMTableModel.get_tables(t_id, pdm_id)
        table_list.append(tables.to_dict())
    data = {
        "tables": table_list,
        "package": package.to_dict()
    }
    print(data.get("package"))
    return render_template('tables.html', data=data)


@app_bp.route('/table/<table_id>/<pack_fid>/<pdm_id>/')
@login_required
def table_detail(table_id, pack_fid, pdm_id):
    tables = PDMTableModel.get_tables(table_id, pdm_id)
    table_info = tables.to_dict()
    print(table_info)
    columns = PDMColumnModel.get_table_id_columns(table_id,pdm_id)

    columns_list = [column.to_dict() for column in columns]

    data = {
        "columns": columns_list,
        "table": table_info
    }
    print(columns_list)
    return render_template('table_structure.html', data=data)

@app_bp.route('/search/', methods=['GET', 'POST'])
@login_required
def search_tables():
    # 获取用户输入的表名
    table_name = request.args.get('table_name', '').strip()

    # 打印调试信息（可选）
    print(f"搜索关键字: {table_name}")
    tables = PDMTableModel.search_tables(table_name)
    table_list = []
    for table in tables:
        table_list.append(table.to_dict())
    data = {
        "table_name": table_name,
        "tables": table_list,
    }
    print(data.get("tables"))
    return render_template('result.html', data=data)

